package com.example.cloud.service.impl;

import com.example.cloud.apis.AccountFeignApi;
import com.example.cloud.apis.StorageFeignApi;
import com.example.cloud.entities.Order;
import com.example.cloud.mapper.OrderMapper;
import com.example.cloud.service.OrderService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @Author: Yun
 * @Date: 2024/4/7
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private AccountFeignApi accountFeignApi;

    @Resource
    private StorageFeignApi storageFeignApi;

    @Override
    @GlobalTransactional(name = "create-order", rollbackFor = Exception.class)
    public void create(Order order) {
        // xid为全局事务id的检查
        String xid = RootContext.getXID();

        // 新建订单
        log.info("----------------开始新建订单,xid=" + xid + "-------------------------");
        // 订单初始状态为0
        order.setStatus(0);
        int result = orderMapper.insertSelective(order);
        // 判断是否插入成功
        Order orderFromDB = null;
        if (result > 0) {
            // 获取刚刚插入的订单信息
            orderFromDB = orderMapper.selectOne(order);
            log.info("-->新建订单成功,orderFromDB: " + orderFromDB);
            System.out.println();

            // 扣减库存
            log.info("--> 订单微服务 开始 扣减Storage库存");
            storageFeignApi.decrease(orderFromDB.getProductId(), orderFromDB.getCount());
            log.info("--> 订单微服务 结束 扣减Storage库存");

            // 减少账户余额
            log.info("--> 订单微服务 开始 扣减Account余额");
            accountFeignApi.decrease(orderFromDB.getUserId(), orderFromDB.getMoney());
            log.info("--> 订单微服务 结束 扣减Account余额");

            // 修改订单状态
            log.info("--> 修改订单状态");
            orderFromDB.setStatus(1);
//            Example example = new Example(Order.class);
//            Example.Criteria criterion = example.createCriteria();
//            criterion.andEqualTo("userId", orderFromDB.getUserId());
            int i = orderMapper.updateByPrimaryKeySelective(orderFromDB);

            log.info("--> 修改订单状态完成");
            log.info("订单信息为:" + orderFromDB);
        }
        log.info("----------------结束新建订单,xid=" + xid + "-------------------------");
    }
}
